//
// Description: 135. 分发糖果
// Created by Loading on 2022/5/4.
//

#include <bits/stdc++.h>

using namespace std;

int candy(vector<int> &ratings) {
    int n = ratings.size();
    int res = 1;
    // 定义最近一次分配的糖果数
    int last = 1;
    // 定义递减序列长度，最近一个递增序列长度
    int decrease = 0, last_increase = 1;
    for (int i = 1; i < n; ++i) {
        if (ratings[i] >= ratings[i - 1]) {
            decrease = 0;
            last = ratings[i] == ratings[i - 1] ? 1 : last + 1;
            // 递增序列长度与最近分配糖果数相同
            last_increase = last;
            res += last;
        } else {
            ++decrease;
            /* 当递减序列长度与最近一个递增序列长度相等时，需要将该递增序列的最大值并入递减序列中，因为需要改变该最大值 */
            if (decrease == last_increase) {
                ++decrease;
            }
            res += decrease;
            last = 1;
        }
    }

    return res;
}

int main() {
    vector<int> ratings{2, 6, 2};
    auto res = candy(ratings);
    cout << res << endl;

    return 0;
}